package de.islanders.world;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.Random;

public class Clock implements Runnable{
	
	private static Clock sClock;
	private List<PropertyChangeListener> listeners;
	
	private int day,
				hours,
				minutes,
				seconds;
	

	private Clock() {
		day = 1;
		hours = new Random().nextInt(24);
		minutes = new Random().nextInt(60);
		seconds = new Random().nextInt(60);
		this.notifyListeners("Daystate", null, hours);
	}

	/**
	 * @return the day
	 */
	public int getDay() {
		return day;
	}

	/**
	 * @return the hours
	 */
	public int getHours() {
		return hours;
	}

	/**
	 * @return the minutes
	 */
	public int getMinutes() {
		return minutes;
	}

	/**
	 * @return the seconds
	 */
	public int getSeconds() {
		return seconds;
	}



	/**
	 * @return Clock singleton
	 */
	public static Clock getInstance() {
		if (sClock == null) {
			sClock = new Clock();
		}
		return sClock;
	}
	
	public void run() {
		try {
			while(!Thread.interrupted()) {
				synchronized(this){
					seconds++;
					if(seconds >= 60){
						seconds = 0;
						minutes++;
						notifyListeners("TideUpdate", minutes - 1, minutes);
						if(minutes >= 60) {
							minutes = 0;
							hours++;
							notifyListeners("Daystate", minutes - 1, minutes);
							//notify DaytimeExchange
							if(hours >= 24) {
								hours = 0;
								day++;
							}
						}
					}
				//	System.out.println(this.toDebugString());
				}
			Thread.sleep(100);
			}
		}catch(InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void addListener(PropertyChangeListener listener){
		listeners.add(listener);
	}
	
	private void notifyListeners(String propertyName, Object oldValue, Object newValue) {
		for(PropertyChangeListener listener : listeners) {
			listener.propertyChange(new PropertyChangeEvent(this, propertyName, oldValue, newValue));
		}
	}
	
	public String toString() {
		return hours + ":" + minutes + " " + seconds;
	}
	
	public String toDebugString() {
		return (hours >= 10 ? "" : "0") + hours + ":"
				+ (minutes >= 10 ? "" : "0") + minutes + ":"
				+ (seconds >= 10 ? "" : "0") + seconds + " "
				+ DaytimeExchange.getInstance().dayStateToString();
	}
}
